package com.silence.demo;

import com.silence.demo.entity.DemoUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * Created by Administrator on 2017/4/18.
 */
@Api(value = "用户", description = "有关于用户的CURD操作" )
@RestController
@RequestMapping(value="/demo/users")     // 通过这里配置使下面的映射都在/demo/users下
public class DemoUserController {

    // 创建线程安全的Map
    static Map<Long, DemoUser> users = Collections.synchronizedMap(new HashMap<Long, DemoUser>());

    @ApiOperation(value="获取用户列表", notes="")
    @RequestMapping(value="/list", method= RequestMethod.GET)
    public List<DemoUser> list(){
        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
        List<DemoUser> r = new ArrayList<DemoUser>(users.values());
        return r;
    }

    @ApiOperation(value="保存用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "DemoUser")
    @RequestMapping(value="/save", method= RequestMethod.POST)
    public String save(@ModelAttribute DemoUser user) {
        // 测试链接
        // http://localhost:1111/demo/users/save?name="zhangsan"&age=2&id=1
        // 除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="获取用户详细信息", notes="根据id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/find", method=RequestMethod.GET)
    public DemoUser find(Long id) {
        // 测试链接
        // http://localhost:1111/demo/users/find?id=1
        // url中的id可通过@PathVariable绑定到函数的参数中
        return users.get(id);
    }

    @ApiOperation(value="删除用户", notes="根据id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    @RequestMapping(value="/delete", method=RequestMethod.GET)
    public String delete(Long id) {
        // 测试链接
        // http://localhost:1111/demo/users/delete?id=1
        users.remove(id);
        return "success";
    }

}
